package com.liusha.quicksand.web;

import com.liusha.quicksand.service.BlogService;
import com.liusha.quicksand.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class BlogIndexController {

//    private HttpServletResponse response;
//
//    @Autowired
//    private UserMapper userMapper;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    /*  网站主页  */
    @GetMapping("/index")
    public String index(@PageableDefault(size = 30, sort = {"updatetime"}, direction = Sort.Direction.DESC) Pageable pageable, Model model,
                        HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals("token")) {
//                    String token = cookie.getValue();
//                    // 进入数据库
//
//                    User user = userMapper.findByToken(token);
//
//                    if (user != null) {
//                        request.getSession().setAttribute("user", user);
//                    }
//                    break;
//                }
//            }
//        }
//        String token = null;
//        response.addCookie(new Cookie("token",token));

        model.addAttribute("page", blogService.listBlog(pageable));

        /*dddd*/
//        model.addAttribute("types",typeService.listTypeTop(20));
        /*dddd*/

        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(10));


        return "index";
    }

    /*全局查询*/
    @PostMapping("/search")
    public String search(@PageableDefault(size = 30, sort = {"updatetime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model) {

        model.addAttribute("page", blogService.listBlog("%" + query + "%", pageable));
        model.addAttribute("query", query);

        return "search";
    }

    /*博客详情页*/
    @GetMapping("/blog/{blogId}")
    public String blog(@PathVariable Long blogId, Model model) {

        model.addAttribute("blog", blogService.getAndConvert(blogId));

        return "blog";
    }
}
